/**
 * Diplomova prace - ukazkovy kod (Zatim poslani dvou AT prikazu a odchytavani odpovedi)
 */

package tcinert;

import com.siemens.icm.io.ATCommand;
import com.siemens.icm.io.ATCommandFailedException;
import com.siemens.icm.io.ATCommandResponseListener;
import javax.microedition.midlet.*;

/**
 * @version 0.1
 * @author Tomas Cnert
 */
public class Diplomka extends MIDlet {
    ATCommand at;
    ATCommandResponseListener listener;
    
    public Diplomka()
    {
        try {
            at = new ATCommand(false); // Promenna ATCommand
        } catch (ATCommandFailedException ex) {     // Zachyceni dvou vyjimek - zatim "nereseno"
            ex.printStackTrace();
        } catch (IllegalStateException ex) {
            ex.printStackTrace();
        }
        listener = new ATCommandResponseListener() {        // Listener na odezvu na AT prikazy

            public void ATResponse(String Response) {       // Metoda na zachyceni odezvyv (pozdeji predelat na switch)
                if (Response.equalsIgnoreCase("ERROR")){    // Pokud vraceno "ERROR" je ukoncen MIDlet
                    destroyApp(true);
                    notifyDestroyed();
                }
               else if(Response.equalsIgnoreCase("+CREG:"))
                {
                   if(!Response.equalsIgnoreCase("+CREG: 1"))       // Pri "1" je GSM modul zaregistrovan
                   {                                                // jiny stav indikuje neprihlaseni se do site
                       destroyApp(true);                            // nebo roaming (neuvazujem za mozne]
                       notifyDestroyed();                           // Akce prozatim "pouhe: ukonceni aplikace
                   }
               }
            }
        };
    }
    /**
     * Metoda na poslani ATprikazu
     * @param ATprikaz
     */
    public void ATsend(String ATprikaz){
        try {
            at.send(ATprikaz, listener);
        } catch (ATCommandFailedException ex) {
            ex.printStackTrace();
        } catch (IllegalStateException ex) {
            ex.printStackTrace();
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
    }

    /**
     *
     */
    public void startApp() {
        try {
            ATsend("OK");
            Thread.sleep(1000);             // Zpozdeni - z duvodu dobz vykonani AT prikazu
                                            // Zatim nastaveno nahodile - postupem casu upresnit
            ATsend("AT+CREG?\r");
            Thread.sleep(1000);


        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
} 